package com.yoshino.book.controller;

import com.google.gson.Gson;
import com.yoshino.book.pojo.Book;
import com.yoshino.book.pojo.Cart;
import com.yoshino.book.pojo.CartItem;
import com.yoshino.book.pojo.User;
import com.yoshino.book.service.BookService;
import com.yoshino.book.service.CartItemService;

import javax.servlet.http.HttpSession;

public class CartController {

    private CartItemService cartItemService;
    private BookService bookService;

    //加载当前用户的购物车信息
    public String index(HttpSession session){
        User user = (User) session.getAttribute("currUser");
        Cart cart = cartItemService.getCart(user);
        user.setCart(cart);
        session.setAttribute("currUser",user);
        return "cart/cart";
    }

    public String addCart(Integer bookId, HttpSession session){
        Object currUser = session.getAttribute("currUser");

        if (currUser != null){
            User user = (User) currUser;
            CartItem cartItem = new CartItem(new Book(bookId),1,user);
            //将指定的图书添加到当前用户的购物车中
            cartItemService.addOrupdateCartItem(cartItem,user.getCart());

            Cart cart = cartItemService.getCart(user);
            user.setCart(cart);
            session.setAttribute("currUser",user);

            return "json:添加成功";
        }


        return "json:请先登录";
    }

    public String editCart(Integer cartItemId, Integer buyCount, Integer bookId, HttpSession session){
        if (bookId != null && (bookService.getBook(bookId).getBookCount() < buyCount)){
            return "json:库存不足";
        }else {
            cartItemService.updateCartItem(new CartItem(cartItemId,buyCount));
            User user = (User)session.getAttribute("currUser");
            Cart cart = cartItemService.getCart(user);
            user.setCart(cart);
            session.setAttribute("currUser",user);
            return "";
        }
    }

    public String delCart(Integer cartItemId, HttpSession session){
        cartItemService.delCart(new CartItem(cartItemId));

        User user = (User)session.getAttribute("currUser");
        Cart cart = cartItemService.getCart(user);
        user.setCart(cart);
        session.setAttribute("currUser",user);
        return "";
    }

    public String cartInfo(HttpSession session){
        User user = (User) session.getAttribute("currUser");
        Cart cart = cartItemService.getCart(user);
        //调用Cart中的是三个属性的get方法，目的是在此处计算这三个属性的值，否则这三个属性为null
        //导致的结果就是下一步的gson转化时，为null的属性会被忽略
        cart.getTotalBookCount();
        cart.getTotalCount();
        cart.getTotalMoney();
        Gson gson = new Gson();
        String cartJsonStr = gson.toJson(cart);
        return "json:" + cartJsonStr;
    }

}
